<template>
    <div class="search-result">
        <van-list 
            v-model="loading" 
            :finished="finished" 
            finished-text="没有更多了" 
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            @load="onLoad"
        >
            <van-cell v-for="article in resultList" :key="article.art_id" :title="article.title" :to="`/article/${article.art_id}`"/>
        </van-list>
    </div>
</template>

<script>
import {getSearchResult} from '@/api/search'

export default {
    name: 'SearchResult',
    props: {
        searchText: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            resultList: [], 
            loading: false, //控制加载中的loading状态
            finished: false, //控制加载结束状态
            error: false, //控制加载失败的提示状态
            page: 1, //页码, 初始为 1
        }
    },
    methods: {
        onLoad() {
            getSearchResult({
                page: this.page, //页码
                per_page: 15, //每页大小
                q: this.searchText //查询关键字
            }).then(({data}) => {
                console.log(data)
                const results = data.data.results
                this.resultList.push(...results)
                // 1 加载状态结束
                this.loading = false;
                // 2 判断数据是否全部加载完成
                if(results.length) {
                    // 有数据,则更新获取下一页
                    this.page++
                } else {
                    // 没有数据了，将 finished 设为 true;
                    this.finished = true
                }
            }).catch((err) => {
                console.log('请求失败', err)
                this.loading = false;
                this.error = true
            })
        },
    }
}
</script>

<style lang="less" scoped>
.search-result {
    // 让search-result区域产生自己的滚动条，这样就不用将顶部的搜索框设置为fixed固定了
    height: 92vh;
    overflow-y: auto;
}
</style>